package Controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"strconv"
	"strings"
	"web_back_go/DAO/gorm"
	"web_back_go/DAO/gorm/GormModel"
	"web_back_go/Dto"
	"web_back_go/Response"
)

func CheckDelivery(c *gin.Context) {
	orderNumberStr := c.Query("orderNumber")
	orderNumber, err := strconv.ParseInt(orderNumberStr, 10, 64)
	db := gorm.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()
	var order GormModel.TzOrder

	//1.select * from tz_order o where o.order_number = #{orderNumber}
	db.Where("order_number =?", orderNumber).First(&order)
	delivery := GormModel.TzDelivery{}
	db.Where("dvy_id =?", order.DvyID).First(&delivery)
	url := strings.Replace(delivery.QueryUrl, "{dvyFlowId}", order.DvyFlowID, -1)
	log.Print("请求物流url: " + url)
	// 发送 GET 请求
	resp, err := http.Get(url)
	if err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "发送请求失败",
		})
		return
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			log.Printf("关闭响应体时出错: %v", err)
		}
	}()
	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "读取响应失败",
		})
		return
	}

	// 处理响应体
	var deliveryJson map[string]interface{}
	err = json.Unmarshal(body, &deliveryJson)
	if err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "解析响应失败",
		})
		return
	}

	// 将解析后的 JSON 数据转换为 DeliveryDto
	var deliveryDto Dto.DeliveryDto
	err = json.Unmarshal(body, &deliveryDto)
	log.Print(deliveryDto.Data)
	if err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Data:    nil,
			Success: true,
			Msg:     "解析响应失败",
		})
		return
	}

	// 设置额外的信息
	deliveryDto.DvyFlowId = order.DvyFlowID
	deliveryDto.CompanyHomeUrl = delivery.CompanyHomeUrl
	deliveryDto.CompanyName = delivery.DvyName

	// 返回响应
	c.JSON(200, Response.ResponseBody{
		Code:    "00000",
		Data:    deliveryDto,
		Success: true,
		Msg:     "获取配送信息成功",
	})
}
